// controllers/tableController.js
const db = require('../config/db');

const tableController = {
  // 获取店铺桌位列表 - 使用 async/await
  getShopTables: async (req, res) => {
    try {
      const { shopId } = req.params;
      console.log('getShopTables 被调用，shopId:', shopId);

      // 1. 查询店铺信息
      const shopQuery = 'SELECT id, name, is_open FROM shop_info WHERE id = ?';
      const [shopResults] = await db.execute(shopQuery, [shopId]);

      if (shopResults.length === 0) {
        return res.status(404).json({
          success: false,
          message: '店铺不存在'
        });
      }

      const shop = shopResults[0];

      // 2. 查询该店铺的所有桌位
      const tableQuery = `
        SELECT * FROM table_info 
        WHERE shop_id = ? AND status != '停用'
        ORDER BY table_type, table_number
      `;
      
      const [tableResults] = await db.execute(tableQuery, [shopId]);

      // 3. 统计桌位状态
      const total_tables = tableResults.length;
      const available_tables = tableResults.filter(table => table.status === '空闲').length;
      const occupied_tables = tableResults.filter(table => table.status === '占用').length;
      const reserved_tables = tableResults.filter(table => table.status === '预留').length;

      const tableStatus = {
        total_tables,
        available_tables,
        occupied_tables,
        reserved_tables
      };

      console.log(`店铺 ${shopId} 的桌位数据:`, {
        总桌位: total_tables,
        可用: available_tables,
        占用: occupied_tables,
        预留: reserved_tables,
        桌位列表: tableResults.map(t => `${t.table_number}(${t.status})`)
      });

      // 4. 返回数据
      res.json({
        success: true,
        message: '获取桌位成功',
        data: {
          shop_info: {
            id: shop.id,
            name: shop.name,
            is_open: shop.is_open
          },
          tables: tableResults,
          table_status: tableStatus
        }
      });

    } catch (error) {
      console.error('获取桌位列表异常:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  },

  // 选择桌位 - 使用 async/await
  selectTable: async (req, res) => {
    try {
      const { tableId } = req.params;
      const userId = req.user ? req.user.id : 1;
      
      console.log('selectTable 被调用，tableId:', tableId, 'userId:', userId);

      // 1. 首先检查桌位是否存在且状态为空闲
      const checkQuery = 'SELECT * FROM table_info WHERE id = ?';
      const [checkResults] = await db.execute(checkQuery, [tableId]);

      if (checkResults.length === 0) {
        return res.status(404).json({
          success: false,
          message: '桌位不存在'
        });
      }

      const table = checkResults[0];

      // 2. 检查桌位状态
      if (table.status !== '空闲') {
        return res.status(400).json({
          success: false,
          message: `该桌位当前${table.status}，无法选择`
        });
      }

      // 3. 更新桌位状态为预留
      const updateQuery = 'UPDATE table_info SET status = "预留", updated_at = NOW() WHERE id = ?';
      await db.execute(updateQuery, [tableId]);

      console.log('桌位选择成功:', tableId);

      // 4. 返回成功响应
      res.json({
        success: true,
        message: '桌位选择成功',
        data: {
          table: {
            id: table.id,
            table_number: table.table_number,
            table_name: table.table_name,
            status: '预留'
          },
          redirect_url: `/menu?table_id=${tableId}&shop_id=${table.shop_id}`
        }
      });

    } catch (error) {
      console.error('选择桌位异常:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  },

  // 释放桌位 - 使用 async/await
  releaseTable: async (req, res) => {
    try {
      const { tableId } = req.params;
      console.log('releaseTable 被调用，tableId:', tableId);

      // 更新桌位状态为空闲
      const updateQuery = 'UPDATE table_info SET status = "空闲", updated_at = NOW() WHERE id = ?';
      await db.execute(updateQuery, [tableId]);

      res.json({
        success: true,
        message: '桌位已释放'
      });
    } catch (error) {
      console.error('释放桌位异常:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  }
};

module.exports = tableController;